/**
 * 
 */
Ext.ns('App', 'App.ratebeli');
/**
 * App.user.Grid
 * A typical EditorGridPanel extension.
 */
App.ratebeli.Grid = Ext.extend(Ext.grid.EditorGridPanel, {
    //renderTo: 'user-grid',
    iconCls: 'silk-grid',
    frame: true,
    //title: 'Users',
    height: 500,

    initComponent : function() {

        // typical viewConfig
        this.viewConfig = {
            forceFit: true
        };

        this.rbproxy = new Ext.data.HttpProxy({
            api: {
		        read : '<?php echo URL::base()?>ratebeli/view',
		        create : '<?php echo URL::base()?>ratebeli/create',
		        update: '<?php echo URL::base()?>ratebeli/update',
		        destroy: '<?php echo URL::base()?>ratebeli/delete'
            }
        });

        // Typical JsonReader.  Notice additional meta-data params for defining the core attributes of your json-response
        this.rbreader = new Ext.data.JsonReader({
            totalProperty: 'total',
            successProperty: 'success',
            //idProperty: 'id',
            root: 'ratebeli'
        }, [
			    {name: 'id'},
			    {name: 'rateimport', allowBlank: false},
			    {name: 'patokan_awal', allowBlank: false},
			    {name: 'patokan_akhir', allowBlank: false},
			    {name: 'booster_admin', allowBlank: false},
			    {name: 'booster_auto', allowBlank: false},
			    {name: 'margin', allowBlank: false},
			    {name: 'diskon', allowBlank: false},
			    {name: 'ratedasarbeli'},
			    {name: 'ratedasarbeliprem'},
			    {name: 'module_id', allowBlank: false}
			]);

        // The new DataWriter component.
        this.rbwriter = new Ext.data.JsonWriter({
            encode: true,
            writeAllFields: true
        });

        // Typical Store collecting the Proxy, Reader and Writer together.
        this.rbstore = new Ext.data.Store({
            id: 'ratebeli',
            proxy: this.rbproxy,
            reader: this.rbreader,
            writer: this.rbwriter,  // <-- plug a DataWriter into the store just as you would a Reader
            autoSave: false,  // <-- false would delay executing create, update, destroy requests until specifically told to do so with some [save] buton.
            listeners: {
                write : function(rbstore, action, result, res, rs) {
                    //App.setAlert(res.success, res.message); // <-- show user-feedback for all write actions
        			//Ext.MessageBox.alert(res.success, res.message);
                },
                exception : function(rbproxy, type, action, options, res, arg) {
        			//Ext.MessageBox.alert('dasdasdasd');
                    if (type === 'remote') {
                        Ext.Msg.show({
                            title: 'REMOTE EXCEPTION',
                            msg: res.message,
                            icon: Ext.MessageBox.ERROR,
                            buttons: Ext.Msg.OK
                        });
                    }
                }
            }
        });

      this.modulestore = new Ext.data.JsonStore({
            url           : '<?php echo URL::base()?>module/view',
            root          : 'module',
            totalProperty : 'total',
            //id            : 'id',
            fields        : ['id', 'menu'],
            remoteSort    : true,
            autoload      : true
        });

        this.modulestore.load(); 
        // A new generic text field
        this.textField =  new Ext.form.TextField();

        Ext.util.Format.comboRenderer = function(cmbField){
            return function(value){
                var record = cmbField.findRecord(cmbField.valueField, value);
                return record ? record.get(cmbField.displayField) : cmbField.valueNotFoundText;
            }
        }


	   this.cmbField = new Ext.form.ComboBox({
	        store: this.modulestore,
	        typeAhead: true,
	        lazyRender:true,
	        displayField: 'menu',
	        valueField: 'id',
	        editable: false,
	        mode: 'remote',
	        forceSelection: true,
	        triggerAction: 'all',
	        selectOnFocus: true
	        
	        });
        // A new generic text field
        this.textField =  new Ext.form.TextField();

        // Let's pretend we rendered our grid-columns with meta-data from our ORM framework.
        this.rbColumns =  [
		    {header: "ID", width: 40, sortable: true, dataIndex: 'id'},
		    {header: "Rate Import", width: 100, sortable: true, dataIndex: 'rateimport', editor: this.textField},
		    {header: "Patokan Awal", width: 100, sortable: true, dataIndex: 'patokan_awal', editor: this.textField},
		    {header: "PAtokan Akhir", width: 100, sortable: true, dataIndex: 'patokan_akhir', editor: this.textField},
		    {header: "Margin", width: 100, sortable: true, dataIndex: 'margin', editor: this.textField},
		    {header: "Diskon", width: 100, sortable: true, dataIndex: 'diskon', editor: this.textField},
		    {header: "Booster Admin", width: 100, sortable: true, dataIndex: 'booster_admin', editor: this.textField},
		    {header: "Booster Auto", width: 100, sortable: true, dataIndex: 'booster_auto', editor: this.textField},
		    {header: "Rate Dasar", width: 100, sortable: true, dataIndex: 'ratedasarbeli'},
		    {header: "Rate Dasar Premium", width: 100, sortable: true, dataIndex: 'ratedasarbeliprem'},
		    {header: "Module", width: 100, sortable: true, dataIndex: 'module_id', editor: this.cmbField, renderer: Ext.util.Format.comboRenderer(this.cmbField)}
		];
        // relay the Store's CRUD events into this grid so these events can be conveniently listened-to in our application-code.
        //this.relayEvents(this.store, ['destroy', 'save', 'update']);
        this.rbstore.load();
        Ext.apply(this, {
    		store: this.rbstore,
    		columns: this.rbColumns,
    		border:false
    	});
        // build toolbars and buttons.
        this.tbar = this.buildTopToolbar();
        this.buttons = this.buildUI();
       // this.bbar = this.buildBottomToolbar();

        // super
        App.ratebeli.Grid.superclass.initComponent.call(this);
    },

    /**
     * buildTopToolbar
     */
    buildTopToolbar : function() {
        return [{
            text: 'Add',
            iconCls: 'silk-add',
            handler: this.onAdd,
            scope: this
        }, '-', {
            text: 'Delete',
            iconCls: 'silk-delete',
            handler: this.onDelete,
            scope: this
        }, '-'];
    },

    buildUI : function() {
        return [{
            text: 'Save',
            iconCls: 'icon-save',
            handler: this.onSave,
            scope: this
        }];
    },

    /**
     * onSave
     */
    onSave : function(btn, ev) {
        this.store.save();
    },

    /**
     * onAdd
     */
    onAdd : function(btn, ev) {
        var u = new this.store.recordType({
            first : '',
            last: '',
            email : ''
        });
        this.stopEditing();
        this.store.insert(0, u);
        this.startEditing(0, 1);
    },

    /**
     * onDelete
     */
    onDelete : function(btn, ev) {
        var index = this.getSelectionModel().getSelectedCell();
        if (!index) {
            return false;
        }
        var rec = this.store.getAt(index[0]);
        this.store.remove(rec);
    }
});

